package com.ruoyi.shop.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.shop.config.ShopParameters;
import com.ruoyi.shop.domain.MessageLog;
import com.ruoyi.shop.mapper.MessageLogMapper;
import com.ruoyi.shop.model.MessageBackInfo;
import com.ruoyi.shop.model.MessageInfo;
import com.ruoyi.shop.service.IMessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @ClassName MessageServiceImpl
 * @Description 短信接口
 * @Author 刘欢
 * @Date 2022/4/1 22:24
 * @Version 1.0.0
 * @Modify Time  Version
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MessageServiceImpl implements IMessageService {

    private final MessageLogMapper messageLogMapper;

    @Override
    public void sendMessage(String content, String phoneNo, String templateId) {

        RestTemplate restTemplate = new RestTemplate();

        //初始化短信发送参数
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setMobile(phoneNo);
        messageInfo.setApikey(ShopParameters.API_KEY);
        messageInfo.setSecret(ShopParameters.SECRET);
        messageInfo.setSignId(ShopParameters.SIGN_ID);
        messageInfo.setTemplateId(templateId);
        messageInfo.setContent(StrUtil.isNotEmpty(content)?content : "111" );

        //初始化短信记录参数
        MessageLog messageLog = new MessageLog();
        Long id = messageLogMapper.getId();
        messageLog.setId(id == null?1L : id);
        messageLog.setMessage(StrUtil.isNotEmpty(content)?content : "template:" + templateId );
        messageLog.setPhoneNo(phoneNo);
        messageLog.setSendTime(DateUtil.date().toString());

        try{
            ObjectMapper objectMapper = new ObjectMapper();
            String message = objectMapper.writeValueAsString(messageInfo);
            log.info("发送报文为:{}", message);
            //发送短信
            MediaType mediaType = MediaType.APPLICATION_JSON;
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(mediaType);
            Long beginTime = System.currentTimeMillis();
            String res = restTemplate.postForObject(ShopParameters.TEMPLATE_SEND_URL, new HttpEntity<>(message, httpHeaders) ,String.class);
            Long endTime = System.currentTimeMillis();
            log.info("返回报文为{}", res);
            MessageBackInfo backInfo = objectMapper.readValue(res, MessageBackInfo.class);
            String success = "0";
            //写入短信记录
            messageLog.setSendStatus(backInfo.getCode());
            if(success.equals(backInfo.getCode())){
                messageLogMapper.insertMessage(messageLog);
                log.info("短信发送成功，耗时：{}", endTime -beginTime);
            }else {
                messageLog.setFailReason(backInfo.getMsg());
                messageLogMapper.insertMessage(messageLog);
                log.error("短信发送失败：{}", backInfo.getMsg());
            }
        }catch (Exception e){
            messageLog.setSendStatus("1");
            messageLog.setFailReason("程序出错，请查看日志文件");
            messageLogMapper.insertMessage(messageLog);
            log.error("发送短信失败：", e);
        }
    }
}
